package com.wanghua.mall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.wanghua.common.dto.es.SkuEsModel;
import com.wanghua.mall.search.config.MallElasticSearchConfig;
import com.wanghua.mall.search.constant.EsConstant;
import com.wanghua.mall.search.service.EsSaveService;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

/**
 * @author wanghua
 * @create 2021-08-27 10:43
 */
@Service
public class EsSaveServiceImpl implements EsSaveService {
    @Resource
    private RestHighLevelClient client;

    //上架商品
    @Override
    public boolean productUp(List<SkuEsModel> skuEsModelList) {
        //建立索引,建立映射关系,在kibana中建立好了

        //保存数据
        //BulkRequest bulkRequest, RequestOptions options
        BulkRequest bulkRequest = new BulkRequest();
        skuEsModelList.forEach((skuEsModel) -> {
            //构造保存请求
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            indexRequest.id(String.valueOf(skuEsModel.getSkuId()));
            String string = JSON.toJSONString(skuEsModel);
            indexRequest.source(string, XContentType.JSON);
            bulkRequest.add(indexRequest);
        });
        try {
            //批量保存
            BulkResponse bulkResponse = client.bulk(bulkRequest, MallElasticSearchConfig.COMMON_OPTIONS);
            //TODO 批量保存是否有错误
            return !bulkResponse.hasFailures();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }
}
